package com.cloud.mkz.core.mvc.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;
import com.cloud.mkz.core.common.exception.SsoException;
import com.cloud.mkz.core.common.utils.RedisUtil;

import cn.hutool.core.util.StrUtil;
import lombok.experimental.UtilityClass;

@UtilityClass
public class PermissionChecker {
	
	/**
	 * 判断请求是否有访问权限
	 * @param request
	 * @param requestUrl
	 * @param redisUtil
	 */
	public void checkPermission(HttpServletRequest request, String requestUrl, RedisUtil redisUtil) {
		HttpSession session = ((HttpServletRequest) request).getSession();
		//所访问的url需要权限控制
    	List<?> mymenuList = (ArrayList<?>)session.getAttribute("Constants.MYCLIENTMENUURL");
    	if(null==mymenuList||mymenuList.size()<1) {
    		throw new SsoException(requestUrl, "donotHaveAccess", "没有任何访问权限");
    	}
    	Object allMenuactionObject = redisUtil.get("SsoConstants.RBAC_DATA_ALLACTION");
    	if(null==allMenuactionObject||StrUtil.isEmpty(allMenuactionObject.toString())) {
    		throw new SsoException(requestUrl, "rbacDataError", "系统缓存数据错误");
    	}
    	Map<String, List<String>> map = JSONObject.parseObject(allMenuactionObject.toString(), Map.class);
    	List<String> tempList = map.get(requestUrl);
    	if(null==tempList||tempList.size()<1) {
    		throw new SsoException(requestUrl, "1-noAccess", "1-没有访问权限");
    	}
    	if(!ifHasPermission(tempList, mymenuList)) {
    		throw new SsoException(requestUrl, "noAccess", "没有访问权限");
    	}
	}
	/**
	 * 判断访问的action对应的菜单是否在权限范围内
	 * @param menuUrls
	 * @param mymenuList
	 * @return
	 */
	public boolean ifHasPermission(List<String> menuUrls, List<?> mymenuList) {
		boolean result = false;
		for(String url:menuUrls) {
			if(mymenuList.contains(url)) {
				result = true;
				break;
			}
		}
		return result;
	}
}
